import React, {PureComponent} from 'react';
import BaseComponent from '../base/BaseComponent';
import {connect} from 'react-redux';
import {
  StyleSheet,
  ImageBackground,
  Platform,
  Text,
  Button,
  TextInput,
  View,
  FlatList,
  RefreshControl,
  TouchableOpacity,
  Image,
  Keyboard,
} from 'react-native';
import PropTypes from 'prop-types';
import {
  TextButton,
  ImageButton,
  LinearBoardButton,
  LinearButton,
} from '../../components/Button';
import I18n from 'react-native-i18n';
import {NormalHeader} from '../../components/NavigationHeader';
import {search, follow, query} from '../../api/user';
import {BASE_API} from '../../config';
import {LinerBoardTextInput} from '../../components/TextInput';

class SearchScreen extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      content: '',
      results: [],
    };
  }

  _renderEmptyView = () => (
    <View
      style={{
        //   backgroundColor: 'yellow',
        width: '100%',
        height: 300,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Image
        style={{width: 95}}
        source={require('../../assets/browser/empty.png')}></Image>
      <Text style={{color: 'white', padding: 20, alignSelf: 'center'}}>
        {I18n.t('common.no_data')}
      </Text>
    </View>
  );
  _renderItemSeparatorComponent = () => (
    <View
      style={{
        height: 0.5,
        backgroundColor: '#979797',
        marginLeft: 20,
        marginRight: 20,
      }}
    />
  );

  _renderItem = (item) => (
    <Item
      item={item}
      onPressItem={() => this._onPressItem(item)}
      follow={this._follow}
    />
  );

  _follow = (item) => {
    console.log('关注');
    console.log(JSON.stringify(item));

    follow({
      userToken: this.props.userInfo.token,
      identify: item.id,
      event: !item.relaction,
    })
      .then((res) => {
        let newReulsts = this.state.results.map((user) => {
          return {
            ...user,
            relaction: user.id == item.id ? !user.relaction : user.relaction,
          };
        });

        this.setState({
          results: newReulsts,
        });
      })
      .catch((err) => {
        console.log('关注错误');
        console.log(err);
      });
  };

  _onPressItem = (item) => {
    console.log(item);
    this._showLoading();

    query({userToken: this.props.userInfo.token, identify: item.item.id})
      .then((res) => {
        this._hideLoading();
        this.props.navigation.navigate('UserInfo', {
          user: res.data,
        });
      })
      .catch((err) => {
        this._hideLoading();
        console.log('查询出错' + err);
      });
  };

  search = () => {
    if (this.state.content.length == 0) {
      this._showAlert({content: I18n.t('search.content')});
      return;
    }
    search({
      userToken: this.props.userInfo.token,
      content: this.state.content,
    }).then((res) => {
      let results = res.data.map((item) => {
        return {
          id: item.identify,
          name: item.nickName,
          userId: item.identify,
          avatar: BASE_API + item.image,
          bio: item.introduction,
          relaction: item.relaction,
        };
      });

      this.setState({
        results,
      });
    });
  };

  renderComponent = () => {
    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Search"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />

        <View style={{margin: 20, flexDirection: 'row', marginBottom: 0}}>
          <LinerBoardTextInput
            placeholder={I18n.t('search.keyword')}
            placeholderTextColor="#a1a1a1"
            onChangeText={(text) => {
              this.setState({
                content: text,
              });
            }}></LinerBoardTextInput>
          <ImageButton
            source={require('../../assets/search/s_search.png')}
            btnStyle={{
              marginTop: 0,
              backgroundColor: '#571DAA',
              width: 40,
              height: 40,
              borderRadius: 22,
              position: 'absolute',
              right: 2,
              top: 2,
            }}
            onPress={this.search}
          />
        </View>
        <FlatList
          style={{flex: 1, marginBottom: 20, marginTop: 0}}
          data={this.state.results}
          keyExtractor={(item, index) => index + 'user'} // 给定的item生成一个不重复的key
          renderItem={this._renderItem}
          ListEmptyComponent={this._renderEmptyView}
          ItemSeparatorComponent={this._renderItemSeparatorComponent}
        />
      </View>
    );
  };
}

class Item extends PureComponent {
  static propTypes = {
    follow: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
  }

  render() {
    const {item, onPressItem} = this.props || {};
    const {name, avatar, bio, userId} = item.item || {};

    return (
      <TouchableOpacity
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          padding: 20,
        }}
        onPress={onPressItem}>
        <Image
          style={{
            width: 66,
            height: 66,
            borderRadius: 33,
          }}
          source={{uri: avatar}}
        />
        <View style={{alignContent: 'center', paddingLeft: 10, flex: 1}}>
          <Text numberOfLines={1}>
            <Text style={{color: '#7204F4', fontSize: 18, fontWeight: 'bold'}}>
              {name}
            </Text>
            <Text style={{color: '#7204F4', fontSize: 14}}> @{userId}</Text>
          </Text>
          <Text style={{marginTop: 4, color: '#A4A4A4'}}>{bio}</Text>
        </View>
        {item.item.relaction == 1 ? (
          <LinearBoardButton
            buttonStyle={{
              width: 120,
              height: 30,
            }}
            text={I18n.t('room.followed')}
            onPress={() => {
              this.props.follow(item.item);
            }}></LinearBoardButton>
        ) : (
          <LinearButton
            buttonStyle={{
              width: 120,
              height: 30,
            }}
            text={I18n.t('room.follow')}
            onPress={() => {
              this.props.follow(item.item);
            }}></LinearButton>
        )}
        {/* <TextButton
          buttonStyle={{
            width: 120,
            height: 30,
            marginTop: 0,
            paddingLeft: 10,
            paddingRight: 10,
            borderRadius: 15,
            borderWidth: 2,
            backgroundColor: item.item.relaction == 1 ? '#FFCB26' : '#fff',
            borderColor: '#FFCB26',
          }}
          text={
            item.item.relaction == 1
              ? I18n.t('room.followed')
              : I18n.t('room.follow')
          }
          onPress={() => {
            this.props.follow(item.item);
          }}
        /> */}
      </TouchableOpacity>
    );
  }
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
});
export default connect(mapStateToProps)(SearchScreen);
